import React from 'react';
import { connect } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Button,
  Input,
  Modal,
  Drawer,
  Space,
  Tag,
  Table,
  Image,
  Checkbox,
  message,
  Dropdown,
  Menu,
  TreeSelect,
  Tabs,
  Form,
  Typography,
  Select,
  Row,
  Col,
} from 'antd';
import moment from 'moment';
import { PlusOutlined, SyncOutlined, DownOutlined, RightOutlined } from '@ant-design/icons';
import Categories from '../admin/categories';
import CourseEditCopy from './components/courseEditCopy';
import CourseApprv from './components/courseApprv';
import UploadUtil from '@/components/UploadUtil';
import CommentList from './CommentList';
import PreviewVideo from './PreviewVideo';
import { FormInstance } from 'antd/lib/form';
const { Option } = Select;
const { Paragraph } = Typography;
const { TabPane } = Tabs;
const currControl = 'Edu_CourseCopy';
// const playerCrt = function (vodid: string) {
//   return (
//     '//1301299150.vod2.myqcloud.com/vod-player/1301299150/' +
//     vodid +
//     '/tcplayer/console/vod-player.html?autoplay=false&width=1280&height=720'
//   );
// };
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      visibleCourse: false,
      visible2: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      keywords: '',

      ageRge: '',
      createdTime: '',
      layout: 'course',
      layoutTags: 'courseTags',
      record: {},
      hideCourseData: false,
      cateid: null,
      visibleComment: false,
      recordId: '',
      titleCourse: '',
      url: '',
      stateKey: -1,
      sortBy: 'creationtime',
    };
  }

  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    this.fetchDatas(0, null, null, null, null, null, 'creationtime', null);
    this.fetchCategory();
  }
  fetchDatas = (
    t: number = 0,
    apprvStaus: any,
    isFree: any,
    isRec: any,
    keywords: any,
    cateid: any,
    sortBy: any,
    ageRge: any,
  ) => {
    this.setState({ loading: true });
    const { pageIndex, pageSize } = this.state;
    var sortmode = 'asc';
    if (sortBy == 'creationtime') {
      sortmode = 'desc';
    }
    let payload: any = {
      SkipCount: (pageIndex - 1) * pageSize,
      MaxResultCount: pageSize,
      keywords,
      cateid,
      ageRge,
      sortBy: sortBy,
      sortmode: sortmode,
    };
    if (t > 0) {
      this.setState({ cateid: null, keywords: '' });
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        keywords,
        cateid,
        sortBy: sortBy,
        sortmode: sortmode,
      };
    }
    if (apprvStaus == 'A') {
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        apprvStaus: 'A',
        keywords,
        cateid,
        sortBy: sortBy,
        sortmode: 'asc',
      };
    }
    if (apprvStaus == 'U') {
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        apprvStaus: 'U',
        keywords,
        ageRge,
        cateid,
        sortBy: sortBy,
        sortmode: sortmode,
      };
    }
    if (apprvStaus == 'R') {
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        apprvStaus: 'R',
        keywords,
        ageRge,
        cateid,
        sortBy: sortBy,
        sortmode: sortmode,
      };
    }
    if (isFree) {
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        isFree: true,
        keywords,
        ageRge,
        cateid,
        sortBy: sortBy,
        sortmode: sortmode,
      };
    }
    if (isRec) {
      payload = {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        isRec: true,
        keywords,
        ageRge,
        cateid,
        sortBy: sortBy,
        sortmode: sortmode,
      };
    }

    this.props
      .dispatch({
        type: 'Abp/getList',
        payload,
        control: "Edu_CourseCopy",
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'course' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  handleDelete = (id: number) => {
    const { stateKey, keywords, cateid, ageRge, sortBy } = this.state;
    this.props.dispatch({
      type: 'Abp/delete',
      payload: { id },
      control: currControl,
    });
    if (stateKey === -1) {
      //全部
      this.fetchDatas(0, null, null, null, keywords, cateid, sortBy, ageRge);
    } else if (stateKey === 1) {
      //免费
      this.fetchDatas(0, null, true, null, keywords, cateid, sortBy, ageRge);
    } else if (stateKey === 2) {
      //推荐
      this.fetchDatas(0, null, null, true, keywords, cateid, sortBy, ageRge);
    } else if (stateKey === 3) {
      //已审核
      this.fetchDatas(0, 'A', null, null, keywords, cateid, sortBy, ageRge);
    } else if (stateKey === 4) {
      //未审核
      this.fetchDatas(0, 'U', null, null, keywords, cateid, sortBy, ageRge);
    } else if (stateKey === 5) {
      this.fetchDatas(0, 'R', null, null, keywords, cateid, sortBy, ageRge);
    }
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  handleAction = (act: string) => {
    const { selectedRowKeys, keywords, cateid, sortBy, ageRge } = this.state;
    if (selectedRowKeys.length <= 0) {
      message.warning('请至少选择一项！');
      return;
    }
    this.props
      .dispatch({
        type: 'Abp/batchAll',
        payload: { ids: selectedRowKeys, act },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas(1, null, null, null, keywords, cateid, sortBy, ageRge);
        }
      });
  };
  handleAct = (id: any, act: string) => {
    const { keywords, ageRge, cateid, sortBy } = this.state;
    this.props
      .dispatch({
        type: 'Abp/batchAll',
        payload: { ids: [id], act },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas(1, null, null, null, keywords, cateid, sortBy, ageRge);
        }
      });
  };
  handleMenuClick = (e: any) => {
    this.handleAction(e.key);
  };
  handleOrder = (e: any) => {
    const { keywords, cateid, ageRge } = this.state;
    this.setState({ sortBy: e });
    this.fetchDatas(0, null, null, null, keywords, cateid, e, ageRge);
  };
  onSearch = (value: any) => {
    var temp = '';
    if (
      value.minAge !== undefined &&
      value.maxAge !== undefined &&
      value.minAge !== '' &&
      value.maxAge !== ''
    ) {
      temp = value.minAge + ',' + value.maxAge;
    }
    const tempKey = value.keywords;
    // if (value.minAge != 'undefined' && value.maxAge != 'undefined') {
    //   temp = value.minAge + ',' + value.maxAge;
    // }
    // console.log(value);

    const { cateid, sortBy } = this.state;
    this.setState({ keywords: tempKey, ageRge: temp,pageIndex:1,pageSize:10, }, () => {
      this.fetchDatas(0, null, null, null, tempKey, cateid, sortBy, temp);
    });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  openModalCourse = (recordCourse: any, layout: string) => {
    this.setState({ visibleCourse: true, disabled: true, recordCourse, layout });
  };
  closeModal = () => {
    this.setState({ visible: false });
  };
  closeModalCourse = () => {
    this.setState({ visibleCourse: false });
  };
  swithVideo = (visible: boolean, record = null) => {
    this.setState({ visible3: visible, record });
  };
  swithComment = (visible: boolean, record: any) => {
    this.setState({ visibleComment: visible, recordId: record });
  };
  swithDrawer = (visible: boolean, record = null) => {
    this.setState({ visible2: visible, record });
  };
  swithModel = (visible: boolean, record = null) => {
    this.setState({ visible4: visible, record });
  };
  onCateSelChange = (value: any) => {
    this.setState({ cateid: value });
  };
  /**控制tab切换 */
  callback = (key: any) => {
    var { keywords, cateid, sortBy, ageRge } = this.state;
    let state: number = parseInt(key);
    if (state === -1) {
      //全部
      this.fetchDatas(0, null, null, null, keywords, cateid, sortBy, ageRge);
    } else if (state === 1) {
      //免费
      this.fetchDatas(0, null, true, null, keywords, cateid, sortBy, ageRge);
    } else if (state === 2) {
      //推荐
      this.fetchDatas(0, null, null, true, keywords, cateid, sortBy, ageRge);
    } else if (state === 3) {
      //已审核
      this.fetchDatas(0, 'A', null, null, keywords, cateid, sortBy, ageRge);
    } else if (state === 4) {
      //未审核
      this.fetchDatas(0, 'U', null, null, keywords, cateid, sortBy, ageRge);
    } else if (state === 5) {
      this.fetchDatas(0, 'R', null, null, keywords, cateid, sortBy, ageRge);
    }
    this.setState({ stateKey: state });
  };
  refresh = () => {
    const { sortBy } = this.state;
    this.setState({pageIndex:1,pageSize:10, })
    this.fetchDatas(1, null, null, null, null, null, sortBy, null);
    this.formRef.current!.resetFields();

  };
  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      totalCount,
      pageSize,
      cascaderOption,
      cateid,
      keywords,
      ageRge,
      stateKey,
      sortBy,
    } = this.state;
    const params = {
      cateid,
      keywords,
      ageRge,
      stateKey,
      sortBy,
    };
    const columns: any = [
      {
        title: '序号',
        width: 60,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '课程图片',
        width: 120,
        dataIndex: 'imageUrl',
        render: (text: string) =>
          text ? <Image width={100} height={60} src={UploadUtil.imgServ + text} /> : null,
      },
      {
        title: '课程名称',
        dataIndex: 'title',
        width: 280,
        render: (text: string, record: any) => (
          <>
            {
              <Paragraph
                copyable={{
                  tooltips: '复制链接',
                  text: `./detail?id=${record.id}`,
                }}
              >
                {text}
              </Paragraph>
            }
          </>
        ),
      },
      {
        title: '审核状态',
        dataIndex: 'apprvStaus',
        width: 100,
        render: (text: string) => (
          <Tag color={text == 'A' ? 'green' : text == 'U' ? 'blue' : 'red'}>
            {text == 'A' ? '已审核' : text == 'U' ? '未审核' : '审核不通过'}
          </Tag>
        ),
      },
      {
        title: '分类',
        width: 130,
        dataIndex: 'categoryName',
        ellipsis: true,
      },
      {
        title: '类型',
        dataIndex: 'cType',
        width: 70,
        render: (text: string) => (
          <Tag color={text == 'video' ? 'blue' : 'pink'}>{text == 'video' ? '视频' : '普通'}</Tag>
        ),
      },
      {
        title: '排序号',
        dataIndex: 'orderId',
        width: 80,
      },
      {
        title: '推荐',
        dataIndex: 'isRec',
        width: 60,
        render: (text: boolean, record: any) => (
          <Checkbox checked={text} onChange={() => this.handleAct(record.id, 'rec')} />
        ),
      },
      {
        title: '置顶',
        dataIndex: 'isTop',
        width: 60,
        render: (text: boolean, record: any) => (
          <Checkbox checked={text} onChange={() => this.handleAct(record.id, 'top')} />
        ),
      },
      {
        title: '免费',
        dataIndex: 'isFree',
        width: 60,
        render: (text: boolean, record: any) => (
          <Checkbox checked={text} onChange={() => this.handleAct(record.id, 'free')} />
        ),
      },
      {
        title: '审核',
        dataIndex: 'isApprv',
        width: 60,
        render: (text: boolean, record: any) => (
          <Checkbox checked={text} onChange={() => this.handleAct(record.id, 'examine')} />
        ),
      },
      {
        title: '标签',
        dataIndex: 'tags',
        ellipsis: true,
      },
      {
        title: '发布时间',
        dataIndex: 'creationTime',
        width: 150,
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
        ellipsis: true,
      },
      {
        title: '操作',
        width: 240,
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <Space>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                <a>删除</a>
              </Popconfirm>
              <a onClick={() => this.swithDrawer(true, record)}>编辑</a>
              {/* <a onClick={() => this.swithModel(true, record)}>审核</a>
              <a onClick={() => this.swithVideo(true, record)}>预览</a>
              <a onClick={() => this.swithComment(true, record.id)}>评论</a> */}
            </Space>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    // const menu = (
    //   <Menu onClick={this.handleMenuClick}>
    //     <Menu.Item key="examine" icon={<RightOutlined />}>
    //       审核
    //     </Menu.Item>
    //     <Menu.Item key="top" icon={<RightOutlined />}>
    //       置顶
    //     </Menu.Item>
    //     <Menu.Item key="rec" icon={<RightOutlined />}>
    //       推荐
    //     </Menu.Item>
    //     <Menu.Item key="free" icon={<RightOutlined />}>
    //       免费
    //     </Menu.Item>
    //   </Menu>
    // );
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Space>
            <Button
              type="primary"
              onClick={() => this.refresh()}
              loading={loading}
              icon={<SyncOutlined />}
            >
              刷新
            </Button>
            {/* <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>
              添加课程
            </Button>
            <Dropdown overlay={menu}>
              <Button>
                操作 <DownOutlined />
              </Button>
            </Dropdown>
            <Button danger onClick={() => this.handleAction('delete')}>
              删除
            </Button>
            <TreeSelect
              allowClear
              style={{ width: 210 }}
              value={cateid}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={cascaderOption}
              placeholder="请选择分类"
              treeDefaultExpandAll
              onChange={this.onCateSelChange}
            /> */}

            <Form ref={this.formRef} onFinish={this.onSearch} style={{ height: 32 }}>
              <Row>
                {/* <Col span={11}> */}
                  {/* <Input.Group compact>
                    <Form.Item name="minAge">
                      <Input
                        style={{ width: 100, textAlign: 'center' }}
                        placeholder="最小天数"
                        allowClear
                      />
                    </Form.Item>
                    <Form.Item name="maxAge">
                      <Input
                        style={{ width: 100, textAlign: 'center' }}
                        placeholder="最大天数"
                        allowClear
                      />
                    </Form.Item>
                  </Input.Group>
                </Col> */}
                <Col span={16}>
                  <Form.Item name="keywords">
                    <Input placeholder="输入关键词搜索" allowClear />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item>
                    <Button
                      type="primary"
                      // icon={<SearchOutlined />}
                      htmlType="submit"
                      title="查询"
                      style={{ zIndex: 3 }}
                    >
                      搜索
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>

            {/* <Button icon={<PlusOutlined />} onClick={() => this.openModal(null, 'course')}>
              课程分类
            </Button>
            <Button icon={<PlusOutlined />} onClick={() => this.openModalCourse(null, 'course')}>
              课程标签
            </Button>
            <Button onClick={() => this.setState({ visible5: true })}>点播平台</Button>
            <Input.Group compact>
              <Select defaultValue="creationtime" onChange={this.handleOrder}>
                <Option value="creationtime">时间排序</Option>
                <Option value="orderid">排序号</Option>
              </Select>
            </Input.Group> */}
          </Space>
        </Card>
        <Card>
          {/* <Tabs defaultActiveKey="-1" onChange={this.callback}>
            <TabPane tab={'全部'} key="-1"></TabPane>
            <TabPane tab={'免费'} key="1"></TabPane>
            <TabPane tab={'推荐'} key="2"></TabPane>
            <TabPane tab={'已审核'} key="3"></TabPane>
            <TabPane tab={'未审核'} key="4"></TabPane>
            <TabPane tab={'审核不通过'} key="5"></TabPane>
          </Tabs> */}
          <Table
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataSource}
            scroll={{ x: '1800' }}
            pagination={{
              onChange: (page, pageSize) => {
                this.setState({ pageIndex: page, pageSize }, () => {
                  // if (stateKey === -1) {
                  //   //全部
                  //   this.fetchDatas(0, null, null, null, keywords, cateid, sortBy, ageRge);
                  // } else if (stateKey === 1) {
                  //   //免费
                  //   this.fetchDatas(0, null, true, null, keywords, cateid, sortBy, ageRge);
                  // } else if (stateKey === 2) {
                  //   //推荐
                  //   this.fetchDatas(0, null, null, true, keywords, cateid, sortBy, ageRge);
                  // } else if (stateKey === 3) {
                  //   //已审核
                  //   this.fetchDatas(0, 'A', null, null, keywords, cateid, sortBy, ageRge);
                  // } else if (stateKey === 4) {
                  //   //未审核
                  //   this.fetchDatas(0, 'U', null, null, keywords, cateid, sortBy, ageRge);
                  // } else if (stateKey === 5) {
                  //   this.fetchDatas(0, 'R', null, null, keywords, cateid, sortBy, ageRge);
                  // }
                  this.fetchDatas(0, null, null, null, keywords, cateid, sortBy, ageRge)
                });
              },
              pageSize,
              pageSizeOptions: ['10', '50', '100', '5000'],
              total: totalCount,
              showTotal: (totalCount) => `总计${totalCount}条数据`,
            }}
          />
        </Card>
        <Modal
          title="课程分类"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={this.closeModal}
          width={700}
          footer={false}
        >
          <Categories layout={this.state.layout} size="small" />
        </Modal>
        <Modal
          title="课程标签"
          visible={this.state.visibleCourse}
          destroyOnClose={true}
          onCancel={this.closeModalCourse}
          width={700}
          footer={false}
        >
          <Categories layout={this.state.layoutTags} size="small" />
        </Modal>
        <Modal
          title="课程预览"
          visible={this.state.visible3}
          bodyStyle={{ padding: 24 }}
          destroyOnClose={true}
          onCancel={() => this.swithVideo(false, null)}
          footer={false}
          width={450}
        >
          <PreviewVideo previewParams={this.state.record} />
        </Modal>
        <Modal
          title="评论列表"
          visible={this.state.visibleComment}
          bodyStyle={{ padding: 24 }}
          destroyOnClose={true}
          onCancel={() => this.swithComment(false, null)}
          footer={false}
          width={690}
        >
          <CommentList record={this.state.recordId} />
        </Modal>
        <Drawer
          width={900}
          placement="right"
          closable={true}
          onClose={() => this.swithDrawer(false)}
          visible={this.state.visible2}
          maskClosable={false}
          mask={false}
          destroyOnClose={true}
        >
          <CourseEditCopy ParentData={this.state.record} fetchDatas={this.fetchDatas} params={params} />
        </Drawer>
        <Modal
          title="课程文章审核"
          visible={this.state.visible4}
          destroyOnClose={true}
          onCancel={() => this.swithModel(false)}
          footer={false}
          width={1200}
        >
          <CourseApprv
            ParentData={this.state.record}
            fetchDatas={this.fetchDatas}
            params={params}
          />
        </Modal>
        <Modal
          title="腾讯点播平台"
          visible={this.state.visible5}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible5: false })}
          footer={false}
          width="100%"
        >
          <iframe
            style={{ border: 'none', width: '100%', height: '75vh', display: 'flex' }}
            src="https://cloud.tencent.com/login/subAccount"
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(ViewPage);
